package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.i18n.I18Config;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Locale;

import static com.github.aloxc.plugin.restplus.i18n.I18Config.ALLOW_LANGUAGE;

/**
 *
 * @author leero
 */
public class HelpListener extends MouseAdapter implements ActionListener {
    private Project project;
    public HelpListener(Project project) {
        this.project = project;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY() + 5;
        JPopupMenu menu = new JPopupMenu();
        I18Config config = new I18Config();
        String locale = config.getLocale();
        for (int i = 0; i < ALLOW_LANGUAGE.length; i++) {
            JMenuItem la = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.switch_language.text.cur_" + ALLOW_LANGUAGE[i].getLanguage()));
            la.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            if (locale.equals(ALLOW_LANGUAGE[i].getLanguage())) {
                la.setIcon(IconLoader.getIcon("/icons/cur.png"));
                la.setForeground(Consts.MAIN_COLOR);
            } else {
                la.setIcon(IconLoader.getIcon("/icons/language_" + ALLOW_LANGUAGE[i].getLanguage() + ".png"));
            }
            if (Locale.CHINESE.getLanguage().equals(ALLOW_LANGUAGE[i].getLanguage())) {
                la.setForeground(Color.RED);
            }
            la.setToolTipText(ALLOW_LANGUAGE[i].getLanguage());
            la.addActionListener(this);
            menu.add(la);
        }
        menu.show((JButton) e.getSource(), x, y);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        JMenuItem source = (JMenuItem)e.getSource();
        String language = source.getText();
        I18Config i18Config = new I18Config();
        if (!language.equals(i18Config.getLocale())) {
            try {
                Desktop.getDesktop().browse(
                        new URL("https://github.com/aloxc/restplushelp/blob/main/readme-" + source.getToolTipText() + ".md").toURI());
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            }
        }
    }
}
